package com.uniledger.exchange.contact;


import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.SearchView;
import android.view.View;

import com.uniledger.commonlib.lazy.LazyFragmentPagerAdapter;
import com.uniledger.commonlib.util.DisplayUtil;
import com.uniledger.exchange.R;
import com.uniledger.exchange.home.scheme.fragment.transfer.TransferFragment;
import com.uniledger.exchange.model.HttpResult;
import com.uniledger.exchange.model.StellarList;
import com.uniledger.exchange.model.api.Api;
import com.uniledger.exchange.model.rx.RxException;
import com.uniledger.exchange.model.rx.RxProgress;
import com.uniledger.exchange.model.rx.RxSchedulers;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import io.reactivex.functions.Consumer;
import me.yokeyword.indexablerv.EntityWrapper;
import me.yokeyword.indexablerv.IndexableAdapter;
import me.yokeyword.indexablerv.IndexableLayout;

/**
 * 联系人页面
 * https://github.com/YoKeyword/IndexableRecyclerView
 */
public class ContactFragment extends TransferFragment implements LazyFragmentPagerAdapter.Laziable {

    @BindView(R.id.index_able_layout)
    IndexableLayout indexableLayout;
    ContactAdapter contactAdapter;

    SearchContactFragment searchContactFragment;
    @BindView(R.id.searchview)
    SearchView mSearchView;

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";


    private String mParam1;
    private String mParam2;


    public ContactFragment() {
        // Required empty public constructor
    }


    public static ContactFragment newInstance(String param1, String param2) {
        ContactFragment fragment = new ContactFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public void getDataList() {
        Api.getService().getBuddyList(1, 20)
                .compose(RxSchedulers.io_main())
                .compose(RxProgress.applyProgressBar(getActivity()))
                .subscribe(new Consumer<HttpResult<StellarList>>() {
                    @Override
                    public void accept(HttpResult<StellarList> httpResult) throws Exception {

                        searchContactFragment = (SearchContactFragment) getChildFragmentManager().findFragmentById(R.id.search_fragment);

                        contactAdapter.setDatas(httpResult.data.contacts, new IndexableAdapter.IndexCallback<UniContact>() {
                            @Override
                            public void onFinished(List<EntityWrapper<UniContact>> datas) {
                                // 数据处理完成后回调
                                searchContactFragment.bindDatas(httpResult.data.contacts);
                            }
                        });
                        // 添加我关心的人
//                        indexableLayout.addHeaderAdapter(new SimpleHeaderAdapter<>(contactAdapter, "☆", "最近转账", initFavDatas()));
                        initSearch();
                    }
                }, new RxException<>(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                }));
    }

    private List<UniContact> initFavDatas() {
        List<UniContact> list = new ArrayList<>();
        list.add(new UniContact("张三", "10000"));
        list.add(new UniContact("李四", "10001"));
        return list;
    }

    private List<UniContact> initDatas() {
        List<UniContact> list = new ArrayList<>();
        // 初始化数据
        List<String> contactStrings = Arrays.asList(getResources().getStringArray(R.array.contact_array));
        List<String> mobileStrings = Arrays.asList(getResources().getStringArray(R.array.mobile_array));
        for (int i = 0; i < contactStrings.size(); i++) {
            UniContact contactEntity = new UniContact(contactStrings.get(i), mobileStrings.get(i));
            list.add(contactEntity);
        }
        return list;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected void parseArguments(Bundle bundle) {

    }

    @Override
    protected void initData() {
        getDataList();
    }

    @Override
    public int getViewResourceId() {
        return R.layout.fragment_contact;
    }

    @Override
    protected void initView() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        indexableLayout.setLayoutManager(manager);
        contactAdapter = new ContactAdapter(getActivity());
        HorizontalDividerItemDecoration decoration = new HorizontalDividerItemDecoration.Builder(getActivity())
                .color(Color.parseColor("#DFDFE0"))
                .size(DisplayUtil.dip2px(getActivity(),1))
                .margin(120, 48)
                .visibilityProvider(contactAdapter)
                .build();

//        indexableLayout.getRecyclerView().addItemDecoration(decoration);

        contactAdapter.setOnItemContentClickListener(new IndexableAdapter.OnItemContentClickListener<UniContact>() {
            @Override
            public void onItemClick(View v, int originalPosition, int currentPosition, UniContact entity) {
//                if (originalPosition >= 0) {
//                    Toast.makeText(getActivity(), "选中:" + entity.nick + "  当前位置:" + currentPosition + "  原始所在数组位置:" + originalPosition, Toast.LENGTH_SHORT).show();
//
//                } else {
//                    Toast.makeText(getActivity(), "选中Header/Footer:" + entity.nick + "  当前位置:" + currentPosition, Toast.LENGTH_SHORT).show();
//                }
                if (mListener != null)
                    mListener.select(entity);
            }
        });

        indexableLayout.setAdapter(contactAdapter);
        indexableLayout.setOverlayStyle_MaterialDesign(Color.RED);
        indexableLayout.setCompareMode(IndexableLayout.MODE_ALL_LETTERS);
    }

    private void initSearch() {
        FragmentManager fragmentManager = getChildFragmentManager();
        fragmentManager.beginTransaction().hide(searchContactFragment).commit();

        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.trim().length() > 0) {
                    if (searchContactFragment.isHidden()) {
                        fragmentManager.beginTransaction().show(searchContactFragment).commit();
                    }
                } else {
                    if (!searchContactFragment.isHidden()) {
                        fragmentManager.beginTransaction().hide(searchContactFragment).commit();
                    }
                }

                searchContactFragment.bindQueryText(newText);
                return false;
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onClick(View v) {

    }
}
